package controllers

import (
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/redis/go-redis/v9"
	"shang/models"
	"strconv"
	"time"
)

type ChannelTopController struct {
	beego.Controller
}

func (t *ChannelTopController) ChannelTop() {
	channelId := t.GetString("channel")
	exists := models.Redis.Exists(context.Background(), "video_channel:"+channelId).Val()
	if exists != 0 {
		result := models.Redis.ZRevRange(context.Background(), "video_channel"+channelId, 0, 10).Val()
		var videoDataAll []models.Video
		for _, v := range result {
			var video models.Video
			json.Unmarshal([]byte(v), &video)
			videoDataAll = append(videoDataAll, video)
		}
		t.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "success",
			"data": videoDataAll,
		}
		t.ServeJSON()
		return
	} else {
		id, _ := strconv.Atoi(channelId)
		top, _ := models.GetTopInfo(models.Video{
			ChannelId: id,
		})
		for _, v := range top {
			marshal, _ := json.Marshal(v)
			models.Redis.ZAdd(context.Background(), "video_channel"+channelId, redis.Z{
				Score:  float64(v.Attendance),
				Member: string(marshal),
			})
			err := models.Redis.Expire(context.Background(), "video_channel"+channelId, time.Minute*10).Err()
			if err != nil {
				t.Data["json"] = map[string]interface{}{
					"code": 400,
					"msg":  "添加过期时间失败",
				}
				t.ServeJSON()
				return
			}
			t.Data["json"] = map[string]interface{}{
				"code": 200,
				"msg":  "success",
				"data": top,
			}
			t.ServeJSON()
		}

	}
}
